package controllers

import (
	"encoding/hex"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"net/http"
)

// Cookie用法
var cookieName string
var cookieValue string

func CookieAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		val, _ := c.Cookie(cookieName)
		if val == "" {
			c.SetCookie(cookieName, cookieValue, 3600, "/", "localhost", true, true)
			fmt.Println("cookie保存完成")
		}
	}
}
func Cookie(c *gin.Context) {
	name := c.Query("name")
	if len(name) <= 0 {
		c.JSON(http.StatusBadRequest, "name数据错误")
		return
	}
	cookieName = "cookie_" + name                                  //cookie的key值
	cookieValue = hex.EncodeToString([]byte(cookieName + "value")) //cookie的value值
	val, _ := c.Cookie(cookieName)
	if val == "" {
		c.String(http.StatusOK, "Cookie:%s已经下发，下次登录有效", cookieName)
		return
	}
	c.String(http.StatusOK, "验证成功，cookie值为：%s", val)
}

// Session用法
// 文档地址：https://github.com/gin-contrib/sessions
var sessionName string  //session的key值
var sessionValue string //session的value值

type MyOption struct {
	sessions.Options
}

func SessionAuth() gin.HandlerFunc {
	store := cookie.NewStore([]byte("session_secret"))
	return sessions.Sessions("mysession", store)
}
func Session(c *gin.Context) {
	name := c.Query("name")
	if len(name) <= 0 {
		c.JSON(http.StatusBadRequest, "name数据错误")
		return
	}
	sessionName = "session_" + name
	sessionValue = "session_value_" + name
	session := sessions.Default(c) //获取的session
	sessionData := session.Get(sessionName)
	if sessionData != sessionValue {
		//保存session
		session.Set(sessionName, sessionValue)
		o := MyOption{}
		o.Path = "/"
		o.MaxAge = 3600 //有效期，单位 s
		session.Options(o.Options)
		session.Save() //保存session
		c.JSON(http.StatusOK, "首次访问，session已经保存")
		return
	}
	c.JSON(http.StatusOK, "访问成功，您的session是："+sessionData.(string))
}
